package com.itic.mall.mobile.pay;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.user.persistence.model.MallUser;

import net.sf.json.JSONObject;


@Controller
@RequestMapping(value="/mobile/zhifubao")
public class ZhifubaoPay
     extends BaseMobileInterface {
	
	@Autowired
	private OrderService orderService;
	
	/**
	 * 异步通知验证签名
	 * @return
	 */
	@RequestMapping(value="success")
	@ResponseBody
	public void success(HttpServletRequest request)throws Exception{
		String result = "fail";
		Map<String, String> paramMap = getParamMap(request);
		AlipayConfig alipayConfig = new AlipayConfig();
		//boolean signVerified = AlipaySignature.rsaChe ckV2(paramMap,alipayConfig.alipay_public_key2_develop, "UTF-8","RSA2");
		boolean signVerified = AlipaySignature.rsaCheckV1(paramMap,alipayConfig.alipay_public_key2, "UTF-8","RSA2");
		if( signVerified && ("TRADE_SUCCESS".equals(paramMap.get("trade_status")) || "TRADE_FINISHED".equals(paramMap.get("trade_status"))) ){
				//获得ORDER——ID
			   String orderId = getCleanParams(request, "out_trade_no");
			   Order order = orderService.get(orderId);
			   
			   
			   
			   if( null != order && "0".equals(order.getStatus()) ){
				   result = paySuccess(order,"支付宝");
			   }
		}
		System.out.println(result);
	}

	/**
	 * pay_type为异步通知的接口方法后缀名
	 * （BuyNewGold，BuyTimeGold,BuyAliveGold,PickGold,ChougZhi）
	 * @param body商品的具体信息
	 * @param subject 商品的标题
	 * @param out_trade_no 订单号
	 * @param total_amout 订单总金额
	 * @return
	 */
	@RequestMapping(value="pay")
	@ResponseBody
	public Map<String,Object> pay( HttpServletRequest request,HttpServletResponse response, String token,String orderId ){
		String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(orderId) ){
				MallUser user = getMallUserByToken(token);
				if( null != user ){
					Order order = verifyOrder(user.getId(),orderId);
					
					if( null != order ){
						
						String total_amout = order.getTotalMoney();
						
						//如果是测试环境，则使用0.01元
						String valueByKey = sysSettingService.getByKey("ZFB_IS_OPEN_TEST");
						if( StringHelper.isNoneBlank(valueByKey) && "1".equals(valueByKey) ){
							total_amout = "0.01";
						}
						
						String body = "用户购买"+order.getTotalProduct()+"件商品，共消费"+order.getTotalMoney()+"元！";
						String subject = "友惠家VIP";
						String out_trade_no = orderId;
						//String pay_type = "支付宝";
						
						 //result = alipay(pay_type,body,subject,out_trade_no,total_amout);
						
						 AlipayConfig alipayConfig = new AlipayConfig();
				         
					     Map<String, String> m = new HashMap<String, String>();

				         m.put("body", body);
				         m.put("subject", subject);
				         m.put("out_trade_no", out_trade_no);
				         m.put("timeout_express", "30m");         
				         m.put("total_amount", total_amout);
				         m.put("seller_id", alipayConfig.partner);
				         m.put("product_code", "QUICK_MSECURITY_PAY");

				         JSONObject bizcontentJson= JSONObject.fromObject(m);

				        
				          
				        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",alipayConfig.app_id,alipayConfig.app_private_key2,"json","UTF-8",alipayConfig.alipay_public_key2,"RSA2");
				        AlipayTradeAppPayRequest aliRequest = new AlipayTradeAppPayRequest();
				        aliRequest.setBizContent(bizcontentJson.toString());
				        
				        String serviceString = alipayConfig.service;
				        //String envir = sysSettingService.getByKey("ZFB_BACK_URL");
				        aliRequest.setNotifyUrl( serviceString );
				        AlipayTradeAppPayResponse aliResponse = alipayClient.sdkExecute(aliRequest);
				       
				        if( aliResponse.isSuccess() ){
				        	//DATA = response.getBody();
				        	result = SUCCESS;
				        	resultMap.put(DATA, aliResponse.getBody());
				        }else{
				        	result = FAIL;
				        }
						
						errorCode = SUCCESS_ERROR_CODE;
				    	errorMsg = SUCCESS_ERROR_MSG;
					}else{
						result = FAIL;
						errorCode = ORDER_NULL_ERROR_CODE;
				    	errorMsg = ORDER_NULL_ERROR_MSG;
					}
				}else{
					result = LOGIN;
					errorCode = LOGIN_ERROR_CODE;
			    	errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("ZhifubaoPay", "pay", e.toString(),"支付宝支付",e);
		}
		resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
	}
	
	
	
	public Map<String,String> getParamMap(HttpServletRequest request){
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		if( null != requestParams ){
			for( Iterator<String> iter = requestParams.keySet().iterator();iter.hasNext();){
				String name = (String)iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for( int i=0;i<values.length;i++){
					valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
				}
				//乱码解决，这段代码再出现乱码时使用。如果masign和sign不相等也可以使用这段代码
				//valueStr=new String(valueStr.getBytes("ISO-8859-1"),"gbk");
				params.put(name,valueStr);
				
			}
		}
		return params;
	}
	

	/**
	 * 退款
	 */
	public void tuiKuan(){
		
	}
	
	
	
	
	/**
	 * 验证订单方法
	 * @param payType
	 * @param orderNum
	 * @return
	 */
	public Order verifyOrder(String userId,String orderId){
		Order order = null;
	    order = orderService.get(orderId);
		//订单是否已支付，订单是否为用户的
		if( null != order ){
			String userId2 = order.getUserId();
			if( userId.equals(userId2) ){
				if( !order.getStatus().equals("0") ){
					order = null;
				}
			}else{
				order = null;
			}
		}
		return order;
		
	}
	
	
}